import { Button, Card, Form, Input, message, Table, Pagination } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import React, { useEffect, useState } from 'react'
import { UserOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons'
import projectApi, { userItemsModel, assignRolesModel } from '@/api/project'
import UserMoedl from './components/usermodel'
import RightModal from './components/rightModal'
export default function User() {
  const [userList, setUserList] = useState<userItemsModel[]>([])
  // 当前页
  const [current, setCurrent] = useState(1)
  // 每页数量
  const [pageSize, setPageSize] = useState(5)
  // 总数
  const [total, setTotal] = useState(0)
  // 用户名
  const [userName, setUserName] = useState('')
  const [selectUser, setSelectUser] = useState<string[]>([])
  const [loading, setLoading] = useState(false)
  // 控制添加修改模态框显示
  const [isUserModelShow, setIsUserModelShow] = useState(false)
  const [editUser, setEditUser] = useState<userItemsModel>()
  // 控制修改权限模态框显示
  const [isRightModalShow, setIsRightModalShow] = useState(false)
  const [isRoleSelect, setIsRoleSelect] = useState<userItemsModel>()
  const [searchUserName, setSearchUserName] = useState('')
  // 获取用户列表
  const reqUserList = async () => {
    try {
      setLoading(true)
      let result = await projectApi.reqUserList(current, pageSize, userName)

      setUserList(result.items)
      setTotal(result.total)
    } catch (error) {
    } finally {
      setLoading(false)
    }
  }
  const rowSelection = {
    onChange: (selectedRowKeys: any[]) => {
      setSelectUser(selectedRowKeys)
    }
  }
  useEffect(() => {
    reqUserList()
  }, [current, pageSize,userName])
  const columns: ColumnsType<any> = [
    {
      width: '80px',
      title: '序号',
      render(a, b, index) {
        return index + 1
      }
    },
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName'
    },
    {
      title: '角色列表',
      dataIndex: 'roleName'
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate'
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified'
    },
    {
      width: '210px',
      align: 'center',
      title: '操作',
      render(row) {
        return (
          <>
            <Form size="small" layout="inline">
              <Form.Item>
                <Button
                  shape="round"
                  icon={<UserOutlined />}
                  onClick={() => {
                    setIsRoleSelect(row)
                    setIsRightModalShow(true)
                  }}
                ></Button>
              </Form.Item>
              <Form.Item>
                <Button
                  shape="round"
                  icon={<FormOutlined />}
                  type="primary"
                  onClick={() => {
                    setEditUser(row)
                    setIsUserModelShow(true)
                  }}
                ></Button>
              </Form.Item>
              <Form.Item>
                <Button shape="round" icon={<DeleteOutlined />} danger onClick={deleteUser(row)}></Button>
              </Form.Item>
            </Form>
          </>
        )
      }
    }
  ]
  // 查找
  const searchUser = () => {
    setUserName(searchUserName)
  }
  // 批量删除
  const deleteAllCheck = async () => {
    try {
      await Promise.all(
        selectUser.map((item) => {
          return new Promise(async (resolve, reject) => {
            try {
              await projectApi.deleteUser(item)
            } catch (error) {
            } finally {
              resolve('1')
              reqUserList()
            }
          })
        })
      )
      message.success('删除成功')
    } catch (error) {}
  }
  const editPage = (current: number, pageSize: number) => {
    setCurrent(current)
    setPageSize(pageSize)
  }
  // 单个删除
  const deleteUser = (user: userItemsModel) => {
    return async () => {
      try {
        await projectApi.deleteUser(user.id!)
        message.success('删除成功')
      } catch (error) {
        message.error(error)
      } finally {
        reqUserList()
      }
    }
  }
  // 添加用户
  const addUser = () => {
    setEditUser({ username: '', nickName: '', password: '' })
    setIsUserModelShow(true)
  }
  const setIsShow = (show: boolean) => {
    setIsUserModelShow(show)
  }
  return (
    <>
      <Card>
        <Form style={{ marginBottom: 20 }} layout="inline">
          <Form.Item>
            <Input
              value={searchUserName}
              onInput={(e) => setSearchUserName((e.target as any).value)}
              placeholder="用户名"
            />
          </Form.Item>
          <Form.Item>
            <Button shape="round" type="primary" onClick={searchUser}>
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              shape="round"
              onClick={() => {
                setUserName('')
              }}
            >
              清空
            </Button>
          </Form.Item>
        </Form>
        <div style={{ marginBottom: 20 }}>
          <Button shape="round" style={{ marginRight: 20 }} type="primary" onClick={addUser}>
            添加
          </Button>
          <Button shape="round" danger disabled={selectUser.length == 0} onClick={deleteAllCheck}>
            批量删除
          </Button>
        </div>
        <Table
          style={{ marginBottom: 10 }}
          pagination={false}
          bordered
          columns={columns}
          rowSelection={rowSelection}
          dataSource={userList}
          rowKey="id"
          loading={loading}
        ></Table>
        <Pagination
          showQuickJumper
          current={current}
          defaultCurrent={current}
          defaultPageSize={pageSize}
          total={total}
          pageSizeOptions={['3', '5', '7']}
          onChange={editPage}
        />
      </Card>
      <UserMoedl
        isShow={isUserModelShow}
        reqUserList={reqUserList}
        userData={editUser}
        setIsShow={setIsShow}
      ></UserMoedl>
      <RightModal
        isShow={isRightModalShow}
        reqUserList={reqUserList}
        isRoleSelect={isRoleSelect}
        setIsShow={(show: boolean) => setIsRightModalShow(show)}
      ></RightModal>
    </>
  )
}
